const hostname = "http://localhost:8777";

const storageHostKey = "redis-gui-hosts";
const RECENTSEARCHLIST = "_RECENT_SEARCH_LIST";
const defaultHostInfo = {
	hostname : "localhost",
	host : "localhost",
	port : 6379,
	db : 0,
	pass : "",
	redisInfoStr:"localhost:6379@/localhost",
	databaseCount : 16,
	selected : false,
	searchKey : "*",
	datas : {
		pageSize : 10,
		nextIndex : 0,
		datalist : []
	}
};
const typeAndContainer = {
		"string":{type:"string", containerType : 0, searchInput: false, tdcount: 2},
		"hash": {type:"table", containerType : 1, searchInput: true, tdcount: 3, ths:["row","field","value", "action"]},
		"list": {type:"table", containerType : 1, searchInput: false, tdcount: 2, ths:["row","value", "action"]},
		"set": {type:"table", containerType : 1, searchInput: true, tdcount: 3, ths:["row","value", "action"]},
		"zset": {type:"table", containerType : 1, searchInput: false, tdcount: 3, ths:["row","value","score", "action"]},
};

//加载本地文件
//function load(name) {
//    let xhr = new XMLHttpRequest(),
//    okStatus = document.location.protocol === "file:" ? 0 : 200;
//    xhr.open('GET', name, false);
//    xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
//    xhr.send(null);
//    return xhr.status === okStatus ? xhr.responseText : null;
//}
//刷新redis基础信息
function refreshRedisKeyspace(redisVue) {
	axios.get(hostname + "/jedis/hostInfo")
		.then(function (response) {
			redisVue.currentHostKeySpace = response.data;
		})
		.catch(function (error) {
			addErrorTaost(redisVue, 'Error! Could not reach the API. ' + error);
		});
}
//更新redishost信息
function initHostDataBase(vueApp, database) {
	// 异步刷新database信息
	setTimeout(function () {
		refreshRedisKeyspace(vueApp);
	}, 10);
	var chindex = vueApp.currentHostIndex;
	vueApp.hostList[chindex].searchKey = "";
	vueApp.hostList[chindex].datas.datalist = [];
	vueApp.currentDatabseIndex = database;
	vueApp.displayLoadingAnimation = true;
	vueApp.recentSearchList = [];
	var selectHost = vueApp.hostList[chindex];
	var recentSearchList = localStorage.getItem(RECENTSEARCHLIST + "_" +selectHost.host +"_" + selectHost.port + "_" + vueApp.currentDatabseIndex);
	if (recentSearchList && recentSearchList.length > 0) {
		var parsedRecentSearch = JSON.parse(recentSearchList);
		vueApp.recentSearchList = parsedRecentSearch;
	}
	axios.get(hostname + "/jedis/selectDb/" + database)
		.then(function (response) {
			var resData = response.data;
			vueApp.hostList[vueApp.currentHostIndex].datas.pageSize = resData.result.length;
			vueApp.hostList[vueApp.currentHostIndex].datas.datalist = resData.result;
			vueApp.hostList[vueApp.currentHostIndex].datas.nextIndex = resData.cursor;
			vueApp.displayLoadingAnimation = false;
		})
		.catch(function (error) {
			addErrorTaost(vueApp, 'Error! Could not reach the API. ' + error);
		});
}
//key信息刷新
function kvrefresh(redisVue) {
	var params = new URLSearchParams();
	params.append("key", redisVue.viewData.key);
	params.append("type", redisVue.keyAndType[redisVue.viewData.key]);
	redisVue.displayLoadingAnimation = true;
	axios.post(hostname + "/jedis/getByType", params)
	.then(function (response) {
		// console.dir(response);
		// console.dir(redisVue.viewData);
	 	var resData = response.data;
	 	if (redisVue.viewData.type == 'string') {
	 		if (typeof(resData)== 'object') {
	 			var jsonVal = JSON.stringify(resData);
		 		redisVue.popWindow.windowContent=jsonVal;
		 		redisVue.popWindow.windowContentNew=jsonVal;
	 		} else {
	 			redisVue.popWindow.windowContent=resData;
	 			redisVue.popWindow.windowContentNew=resData;
	 		}
	 	} else {
	 		redisVue.popWindow.windowContent=resData;
	 	}
	 	if (redisVue.viewData.type == 'hash' || redisVue.viewData.type == 'set') {
			redisVue.popWindow.windowContentCursor = resData.cursor;
		} else if (redisVue.viewData.type != 'string') {
			redisVue.popWindow.windowContentCursor = resData.length;
		}
	 	redisVue.displayLoadingAnimation = false;
	})
	.catch(function (error) {
		addErrorTaost(redisVue, 'Error! Could not reach the API. ' + error);
	});
	axios.post(hostname + "/jedis/getRedisKeysInfo", params)
	.then(function (response) {
	 	redisVue.viewData = response.data
	})
	.catch(function (error) {
		addErrorTaost(redisVue, 'Error! Could not reach the API. ' + error);
	});
}
//查看指定的key
function viewKey (redisVue, key, keyType) {
	redisVue.popWindow.windowContent="";
	redisVue.popWindow.windowContentNew="";
	var openWindowObj = openWindow(1, "数据查看",keyType);
	openWindowObj["windowContentType"] = typeAndContainer[redisVue.keyAndType[key]].containerType;
	redisVue.popWindow = openWindowObj;
	var params = new URLSearchParams();
	params.append("key", key);
	params.append("type", redisVue.keyAndType[key]);
	redisVue.displayLoadingAnimation = true;
	axios.post(hostname + "/jedis/getByType", params)
	.then(function (response) {
		 var resData = response.data;
		 if (!resData) {
			addErrorTaost(redisVue, 'key not found!');
			return;
		 }
	 	if (redisVue.viewData.type == 'string') {
	 		if (typeof(resData)== 'object') {
	 			var jsonVal = JSON.stringify(resData);
		 		redisVue.popWindow.windowContent=jsonVal;
		 		redisVue.popWindow.windowContentNew=jsonVal;
	 		} else {
	 			redisVue.popWindow.windowContent=resData;
	 			redisVue.popWindow.windowContentNew=resData;
	 		}
	 	} else {
	 		redisVue.popWindow.windowContent=resData;
	 	}
	 	if (redisVue.viewData.type == 'hash' || redisVue.viewData.type == 'set') {
			redisVue.popWindow.windowContentCursor = resData.cursor;
		} else if (redisVue.viewData.type != 'string') {
			redisVue.popWindow.windowContentCursor = resData.length;
		}
	 	redisVue.displayLoadingAnimation = false;
	})
	.catch(function (error) {
		addErrorTaost(redisVue, 'Error! Could not reach the API. ' + error);
	});
	axios.post(hostname + "/jedis/getRedisKeysInfo", params)
	.then(function (response) {
	 	redisVue.viewData = response.data
	})
	.catch(function (error) {
		addErrorTaost(redisVue, 'Error! Could not reach the API. ' + error);
	});
}
//添加报错的toast
function addErrorTaost(redisVue,message) {
	addTaost(redisVue,message, -1)
}
// 添加成功的toast
function addSuccessTaost(redisVue,message) {
	addTaost(redisVue,message, 1)
}
// 添加toast
function addTaost(redisVue,message, type) {
	var ntoast = {message : message, type : type};
	var count = redisVue.toastMessages.push(ntoast);
	var ntoastIndex = count - 1;
	setTimeout(function(){
		redisVue.toastMessages.splice(ntoastIndex, 1);
	}, 3000);
	redisVue.displayLoadingAnimation = false;
}
// 根据字符串添加redis服务信息
function addRedisHostByInput(vueApp) {
	vueApp.addHostInfo["host"] =  vueApp.inputHostInfo.host;
	vueApp.addHostInfo["port"] = vueApp.inputHostInfo.port;
	vueApp.addHostInfo["pass"] =  vueApp.inputHostInfo.password;
	vueApp.addHostInfo["hostname"] =  vueApp.inputHostInfo.alias;
	vueApp.addHostInfo["redisInfoStr"] = vueApp.inputHostInfo.host + ":" + vueApp.inputHostInfo.port + "@" + vueApp.inputHostInfo.password + "/" + vueApp.inputHostInfo.alias;
	addRedisHost(vueApp)
}
// 根据字符串添加redis服务信息
function addRedisHostStr(vueApp, hostinfo) {
	var hostdatas = hostinfo.split(":");
	var portAndPass = hostdatas[1].split("@");
	var passAndName = portAndPass[1].split("/");
	//console.log(hostdatas[0] + "," + portAndPass[0] + "," + passAndName[0] + "," + passAndName[1]);
	vueApp.addHostInfo["host"] =  hostdatas[0];
	vueApp.addHostInfo["port"] = portAndPass[0];
	vueApp.addHostInfo["pass"] =  passAndName[0];
	vueApp.addHostInfo["hostname"] =  passAndName[1];
	vueApp.addHostInfo["redisInfoStr"] = hostinfo;
	addRedisHost(vueApp)
}
// 添加redis服务信息
function addRedisHost(vueApp) {
	var saveHosts = localStorage.getItem(storageHostKey);
	if (saveHosts && saveHosts.length > 0) {
		var parsedHosts = JSON.parse(saveHosts);
		const hostLen =  parsedHosts.length;
		var isExist = false;
		for(var i = 0; i < hostLen; i++) {
			var hostitem = parsedHosts[i];
			var redishosturl = vueApp.addHostInfo.host + ":" + vueApp.addHostInfo.port;
			var cachedHostUrl = hostitem.host + ":" + hostitem.port;
			if (hostitem.hostname == vueApp.addHostInfo.hostname ||
					cachedHostUrl == redishosturl) {
				isExist = true;
				break;
			}
		}
		if (isExist) {
			alert("hostname/host:port已存在！");
		} else {
			var nhost = {};
			for(var attr in vueApp.addHostInfo) {
				nhost[attr] = vueApp.addHostInfo[attr];
			}
			parsedHosts.push(nhost);
			localStorage.setItem(storageHostKey, JSON.stringify(parsedHosts));
			vueApp.hostList = parsedHosts;
			vueApp.addWindow = false;
		}
	} else {
		var nhost = {};
		for(var attr in vueApp.addHostInfo) {
			nhost[attr] = vueApp.addHostInfo[attr];
		}
		vueApp.hostList.push(nhost);
		vueApp.currentHostIndex = 0;
		vueApp.currentDatabseIndex = 0;
		localStorage.setItem(storageHostKey, JSON.stringify(vueApp.hostList));
		vueApp.addWindow = false;
	}
}

function searchByKey(redisVue, needCacheToLocal) {
	if(!redisVue.functionClickable) {
		alert("please wait for change host complete!");
		return;
	}
	var chindex = redisVue.currentHostIndex;
	var chost = redisVue.hostList[chindex];
	if (!chost) {
		return;
	}
	var searchPattern = chost.searchKey;
	if (!searchPattern || searchPattern.length == 0) {
		searchPattern = "*";
	} else if (needCacheToLocal) {
		var isNeedCached = true;
		redisVue.recentSearchList.forEach(function (v, index) {
			if (isNeedCached && searchPattern == v) {
				isNeedCached = false;
			}
		});
		if (isNeedCached) {
			redisVue.recentSearchList.unshift(searchPattern);
		}
		if (redisVue.recentSearchList.length >= 10) {
			redisVue.recentSearchList.pop();
		}
		localStorage.setItem(RECENTSEARCHLIST + "_" +chost.host +"_" + chost.port + "_" + redisVue.currentDatabseIndex,
				JSON.stringify(redisVue.recentSearchList));
	}
	redisVue.displayLoadingAnimation = true;
	var params = new URLSearchParams();
	params.append("keyPattern", searchPattern);
	axios.post(hostname + "/jedis/scan/0/", params)
	.then(function (response) {
		var resData = response.data;
		chost.datas.pageSize = resData.result.length;
		chost.datas.datalist = resData.result;
		chost.datas.nextIndex = resData.cursor;
		redisVue.displayLoadingAnimation = false;
	})
	.catch(function (error) {
		addErrorTaost(redisVue,'Error! Could not reach the API. ' + error);
	});
}
function searchByrecentStr(redisVue, searchStr) {
	var chindex = redisVue.currentHostIndex;
	var chost = redisVue.hostList[chindex];
	if (!chost) {
		return;
	}
	chost.searchKey = searchStr;
	searchByKey(redisVue, false);
}
//清除最近搜索历史
function clearRecentHistoryCach (redisVue) {
	var chindex = redisVue.currentHostIndex;
	var chost = redisVue.hostList[chindex];
	if (!chost) {
		return;
	}
	redisVue.recentSearchList = [];
	localStorage.removeItem(RECENTSEARCHLIST + "_" +chost.host +"_" + chost.port + "_" + redisVue.currentDatabseIndex,
			JSON.stringify(redisVue.recentSearchList));
}
//打开redis key添加窗口
function openAddKeyWindow(vueApp) {
	vueApp.addKeyAndValue.key = "";
	vueApp.addKeyAndValue.type = "";
	vueApp.addKeyAndValue.value = "";
	vueApp.addKeyAndValue.score = 0;
	vueApp.addKeyAndValue.field = "";
	vueApp.addKeyWindow = true;
}